#include "ucombobox.h"
#include "modelview/ulistview.h"
#include "modelview/udelegate.h"
#include "style/uproxystyle.h"

#include <QStylePainter>
#include <QPainterPath>

UComboBox::UComboBox(QWidget* parent) : QComboBox(parent)
{
    auto view = new UListView(this);
    auto delegate = new StyledDelegate(view);
    delegate->setItemRadius(0);
    view->setItemDelegate(delegate);
    setView(view);
    setMinimumSize(100, 30);
}

void UComboBox::paintEvent(QPaintEvent* e)
{
    QStylePainter painter(this);
    painter.setRenderHints(QStylePainter::Antialiasing | QStylePainter::SmoothPixmapTransform);
    painter.setPen(palette().color(QPalette::Text));

    QStyleOptionComboBox opt;
    initStyleOption(&opt);

    QRect rect = style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SubControl::SC_ComboBoxArrow, this);
    painter.save();
    QPainterPath path;
    path.addRoundedRect(opt.rect, 4, 4);
    painter.setClipPath(path);

    QColor backgroudColor = palette().color(QPalette::Button);
    QColor color = backgroudColor.darker(110);
    painter.setPen(Qt::NoPen);
    if (opt.state & QStyle::State_MouseOver)
    {
        color = palette().color(QPalette::WindowText);
    }
    if (opt.state & QStyle::State_On)
    {
        color = palette().color(QPalette::Highlight);
    }

    painter.setPen(QPen(color, 2));
    painter.setBrush(backgroudColor);
    painter.drawRoundedRect(opt.rect.adjusted(1, 1, -1, -1), 4, 4);
    painter.restore();

    QIcon icon = (opt.state & QStyle::State_On) ? QIcon::fromTheme("utk_arrowup") : QIcon::fromTheme("utk_arrowdown");
    uint alignment = style()->visualAlignment(Qt::LeftToRight, Qt::AlignLeft | Qt::AlignVCenter);
    painter.drawItemPixmap(rect, alignment, UProxyStyle::getIconPixmap(opt.state, icon, QSize(16, 16)));

    painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}
